package model

import (
	"app/common/response"
	"app/pkg/db"
	"math"

	"gorm.io/gorm"
)

type LocationModel struct {
	CommonStruct
	UserId   int64  `gorm:"column:user_id" json:"user_id"`   //用户ID
	Name     string `gorm:"column:name" json:"name"`         //姓名
	Phone    string `gorm:"column:phone" json:"phone"`       //手机号
	Location string `gorm:"column:location" json:"location"` //地址
	Tag      string `gorm:"column:tag" json:"tag"`           //标签
}

func NewLocationModel() *LocationModel {
	return &LocationModel{}
}

func (m *LocationModel) TableName() string { return "location" }

func (m *LocationModel) Info(uid int64) (info LocationModel, err error) {
	conn, err := db.DB.MysqlDB.DefaultGormDB()
	if err != nil {
		return
	}

	err = conn.Model(m).Where("user_id=?", uid).Order("id desc").Take(&info).Error
	return
}

func (m *LocationModel) List(uid int64, page, limit int) (list []LocationModel, paginate response.Paginate, err error) {
	paginate.Limit = limit
	paginate.Page = page
	conn, err := db.DB.MysqlDB.DefaultGormDB()
	if err != nil {
		return
	}
	conditionRst := func() func(db *gorm.DB) *gorm.DB {
		return func(db *gorm.DB) *gorm.DB {
			if uid > 0 {
				db.Where("uid = ?", uid)
			}
			return db
		}
	}()
	err = conn.Table(m.TableName()+" t").
		Scopes(PaginateScope(page, limit), conditionRst).
		Order("id desc").
		Find(&list).Error
	if err == nil {
		var count int64
		err = conn.Table(m.TableName() + " t").
			Scopes(conditionRst).Count(&count).Error
		if err == nil {
			paginate.Total = count
			total := float64(count) / float64(int64(limit))
			paginate.Pages = int(math.Ceil(total))
		}
	}
	return
}
